<?php
class StatMultiPeriodDataAction extends CAction {
	public function run($node) {
		$statModel = new AccountTokenMultiPeriodStat();
		$statModel->unsetAttributes(); // clear any default values
		$statModel->attributes = $_GET;
		if (!$statModel->validate()) {
			return;
		}
		$node = intval($node);
		$model = AccountTokenCategory::model();
		$criteria = new CDbCriteria();
		if ($node) {
			$criteria->compare('parentId', $node);
		} else {
			$criteria->addInCondition('parentId', array(
					null
				));
		}
		$categories = $model->findAll($criteria);
		$result = array();
		$itemModel = AccountTokenItem::model();
		$commandBuilder = Yii::app()->db->getSchema()->getCommandBuilder();
		$formatter = Yii::app()->format;
		foreach ($categories as $category) {
			$lastSum = $category->getLastSum($statModel->tokenDateStart, $statModel->projectId);
			$criteria = $statModel->createCriteria();
			$criteria->join = 'INNER JOIN {{account_token}} as token on tokenId=token.id INNER JOIN {{account_token_category}} as category on categoryId=category.id';
			$criteria
				->addInCondition('category.id',
					CMap::mergeArray(
						preg_split('/[\|]+/', $category->childrenCache, -1, PREG_SPLIT_NO_EMPTY),
						array(
							$category->id
						)));
			$criteria->select = 'sum(debit) as totalDebit, sum(credit) as totalCredit';
			$command = $commandBuilder->createFindCommand($itemModel->getTableSchema(), $criteria);
			$row = $command->queryRow();
			if ($lastSum == 0 && $row['totalDebit'] == 0 && $row['totalCredit'] == 0) {
				continue;
			}
			$diff = $row['totalDebit'] - $row['totalCredit'];
			$totalSum = $lastSum + $row['totalCredit'] - $row['totalDebit'];
			$result[] = array(
				'id' => $category->id,
				'name' => $category->name,
				'lastDirection' => $lastSum > 0 ? '贷' : ($lastSum < 0 ? '借' : '平'),
				'lastSum' => abs($lastSum),
				'totalDebit' => $row['totalDebit'],
				'totalCredit' => $row['totalCredit'],
				'direction' => $diff > 0 ? '借' : ($diff < 0 ? '贷' : '平'),
				'currentSum' => abs($diff),
				'totalDirection' => $totalSum > 0 ? '贷' : ($totalSum < 0 ? '借' : '平'),
				'totalSum' => abs($totalSum),
				'iconCls' => 'icon-folder-table',
				'leaf' => empty($category->childrenCache),
			);
		}
		JHTML::jsonHeader();
		echo CJSON::encode($result);

	}
}
